package com.itserver.utils;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class RequestHeader {
    // 使用配置获取头部字段
    private static String AUTHORIZATION ;
    @Autowired
    public RequestHeader(Config config){
        AUTHORIZATION = config.getAuthentication();
    }

    // 获取用户id
    public static Integer getUserId(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null; // 如果没有请求上下文，返回 null
        }
        // 获取 HttpServletRequest
        HttpServletRequest request = attributes.getRequest();
        // 获取 Authorization 请求头
        String  authorization = request.getHeader(AUTHORIZATION);
        // 解析 JWT 获取 payload 中的数据
        Claims claims = JwtUtils.parseJWT(authorization);
        if (claims != null) {
            return (Integer) claims.get("id");
        }
        return null;
    }
    // 获取请求头信息
    public static String getRequestHeader(String key){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null; // 如果没有请求上下文，返回 null
        }
        // 获取 HttpServletRequest
        HttpServletRequest request = attributes.getRequest();
        return request.getHeader(key);
    }
    // 解密token 获取用户信息
    public static Claims getUserInfo(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null; // 如果没有请求上下文，返回 null
        }
        // 获取 HttpServletRequest
        HttpServletRequest request = attributes.getRequest();
        // 获取 Authorization 请求头
        String  authorization = request.getHeader(AUTHORIZATION);
        // 解析 JWT 获取 payload 中的数据
        return JwtUtils.parseJWT(authorization);
    }
}
